package furniture.Controller.Background;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;





import framework.base.common.Pager;
import framework.base.controller.BaseController;
import furniture.Bean.CardBean;
import furniture.Common.Impl.CommonFunImpl;
import furniture.Service.ICardService;

@Controller
@RequestMapping("/b_card")
public class CardController extends BaseController{

	/**
	 * 账号控制层
	 */
	private static final long serialVersionUID = 1L;

	@Autowired
	ICardService cardService;
	

	@Override
	public void setLogger() {
	}
	
	@RequestMapping("/index")
	public ModelAndView index(CardBean bean, Pager<CardBean> pager){
		ModelAndView modelAndView = new ModelAndView("background/card/index");
		pager = cardService.selectPage(bean, pager);
		modelAndView.addObject("pager", pager);
		return modelAndView;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(){
		ModelAndView modelAndView = new ModelAndView("background/card/add");
		modelAndView.addObject("listBank", getBank());
		return modelAndView;
	}
	
	@RequestMapping("/edit")
	public ModelAndView edit(CardBean bean){
		ModelAndView modelAndView = new ModelAndView("background/card/edit");
		bean = cardService.selectOne(bean);
		modelAndView.addObject("bean", bean);
		modelAndView.addObject("listBank", getBank());
		return modelAndView;
	}
	
	@RequestMapping("/insert")
	public void insert(CardBean bean, HttpServletResponse response){
		response.setContentType("text/html");
		bean.setId(CommonFunImpl.uuid("C"));
		bean.setInserttime(CommonFunImpl.currentTime(1));
		String arr[] = bean.getBankname().split(";");
		bean.setBankname(arr[1]);
		bean.setPicpath(arr[0] + ".png");
		String ret = cardService.insert(bean) > 0 ? "1" : "0";
		JSONObject jb = new JSONObject();
		jb.put("ret", ret);
		ret = jb.toString();
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/update")
	public void update(CardBean bean, HttpServletResponse response){
		response.setContentType("text/html");
		bean.setInserttime(CommonFunImpl.currentTime(1));
		String arr[] = bean.getBankname().split(";");
		bean.setBankname(arr[1]);
		bean.setPicpath(arr[0] + ".png");
		String ret = cardService.update(bean) > 0 ? "1" : "0";
		JSONObject jb = new JSONObject();
		jb.put("ret", ret);
		ret = jb.toString();
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private List<String> getBank(){
		List<String> list = new ArrayList<String>();
		list.add("95566;中国银行");
		list.add("95599;中国农业银行");
		list.add("95533;中国建设银行");
		list.add("95588;中国工商银行");
		list.add("95559;交通银行");
		list.add("95555;招商银行");
		list.add("95580;中国邮政储蓄银行");
		return list;
	}
	
	@RequestMapping("/delete")
	public void Delete(CardBean bean, HttpServletResponse response) {
		response.setCharacterEncoding("UTF-8");
		int ret = cardService.delete(bean)>0 ? 1 : 0;
		// 以流的形式返回
		try {
			PrintWriter out = response.getWriter();
			
			out.print(ret);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 客户端
	 */
	@RequestMapping("/c_index")
	public ModelAndView c_index(){
		ModelAndView modelAndView = new ModelAndView("front/card/index");
		List<CardBean> list = cardService.selectList(null);
		modelAndView.addObject("list", list);
		return modelAndView;
	}
	
	/**
	 * 获取银行卡账号
	 * 
	 */
	@RequestMapping("/c_getcardid")
	public void getCardId(CardBean bean,String userphone,HttpServletResponse response,HttpSession session){
				
		bean = cardService.selectOne(bean);
		/*
		 *天翼平台 
		 */
		//首先获取access_token
		//String url_access_token = "https://oauth.api.189.cn/emp/oauth2/v3/access_token";
//		StringBuilder sb_access_token = new StringBuilder();
//		sb_access_token.append("grant_type=client_credentials&");
//		sb_access_token.append("app_id=350079670000043451&");
//		sb_access_token.append("app_secret=8be454633574cc390c1f23d293c61607");
//		String param_access_token = sb_access_token.toString();
		//String ret_access_token = sendPost(url_access_token, param_access_token);
		//进行JSON解析
		//String access_token = ParseJson(ret_access_token);
		
		//发送模板短信
		String ret = "-1";
		/*if (!"0".equals(access_token)) {
			String url ="http://api.189.cn/v2/emp/templateSms/sendSms";
			StringBuilder sb = new StringBuilder();
			sb.append("acceptor_tel=");//获取的手机号
			sb.append(userphone);
			sb.append("&template_id=91005477");//模板id
			sb.append("&app_id=350079670000043451");//应用id
			sb.append("&access_token=");//通行证
			sb.append(access_token);
			//添加参数
			sb.append("&template_param=");
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("userid", ((UserBean)session.getAttribute("user_session")).getUserid());
			
			jsonObject.put("bankname", bean.getBankname());
			jsonObject.put("cardid", bean.getCardid());
			jsonObject.put("cardname", bean.getCardname());
			sb.append(jsonObject.toString());
			sb.append("&timestamp=");//时间戳
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
			String nowTime = dateFormat.format(new Date());
			sb.append(nowTime);
			String param = sb.toString();
			String tmpRet = sendPost(url,param);
			JSONObject jo = JSONObject.fromObject(tmpRet);
	        ret = jo.getString("res_code");
		}*/
		ret = "0";
		
		response.setCharacterEncoding("UTF-8");
		// 以流的形式返回
		try {
			PrintWriter out = response.getWriter();
			out.print(ret);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	
	/**
     * 向指定 URL 发送POST方法的请求
     * 
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }
    
    
    public String ParseJson(String jsonString) {

    	String ret = "0";
        JSONObject jo = JSONObject.fromObject(jsonString);
        String res_code = jo.getString("res_code");
        if ("0".equals(res_code)) {
			ret = jo.getString("access_token");
		}
        return ret;
    }
}
